package com.beiing.tianshuai.tianshuai.adapter;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.entity.DynamicDetailBean;
import com.beiing.tianshuai.tianshuai.util.DateUtil;
import com.beiing.tianshuai.tianshuai.util.EmotionUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;
import com.qmuiteam.qmui.span.QMUITouchableSpan;
import com.qmuiteam.qmui.widget.textview.QMUISpanTouchFixTextView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by magikliu on 2017/8/21.
 */

public class CommentReplyAll_RVAdapter extends RecyclerView.Adapter<CommentReplyAll_RVAdapter.mViewHolder> implements View.OnClickListener {

    private Context mContext;
    private List<DynamicDetailBean.DataBean.CommentBean.ReplyBean> mData = new ArrayList<>();
    private LayoutInflater inflater;
    private OnItemClickListener mOnItemClickListener;
    private TextClickListener mTextClickListener;

    public CommentReplyAll_RVAdapter(Context mContext, List<DynamicDetailBean.DataBean.CommentBean.ReplyBean> mData) {
        this.mContext = mContext;
        this.mData = mData;
        inflater = LayoutInflater.from(mContext);
    }

    @Override
    public mViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.item_comment_reply, parent, false);
        mViewHolder mHolder = new mViewHolder(view);
        return mHolder;
    }

    @Override
    public void onBindViewHolder(mViewHolder holder, int position) {
        final int i = mData.size() - position - 1;
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
        String fName = mData.get(i).getFName();
        stringBuilder.append(TextUtils.isEmpty(fName) ? "" : fName);
        stringBuilder.append("回复");
        String tName = mData.get(i).getTName();
        stringBuilder.append(TextUtils.isEmpty(tName) ? "" : tName);
        stringBuilder.append(":");
        String contentDecode = null;
        try {
            contentDecode = URLDecoder.decode(mData.get(i).getContent(), "UTF-8");
            stringBuilder.append(contentDecode);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        stringBuilder.append("  " + getTime(mData.get(i).getCreateTime()));
        if (mData.get(i).getFormUid().equals(SPUtils.getString(mContext, "uid", null))) {
            stringBuilder.append("  " + "删除");
        }

        //表情拼接
        Resources res = mContext.getResources();
        String regexEmotion = "\\[([\u4e00-\u9fa5\\w+\\.])+\\]";
        Pattern patternEmotion = Pattern.compile(regexEmotion);
        Matcher matcherEmotion = patternEmotion.matcher(stringBuilder);
        while (matcherEmotion.find()){
            // 获取匹配到的具体字符
            String key = matcherEmotion.group();
            // 匹配字符串的开始位置
            int start = matcherEmotion.start();
            // 利用表情名字获取到对应的图片
            Integer imgRes = EmotionUtils.getImgByName(key);
            if (imgRes != null) {
                // 压缩表情图片
                int size = (int) holder.tvReply.getTextSize() * 13 / 10;
                Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes);
                Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);

                ImageSpan span = new ImageSpan(mContext, scaleBitmap);
                stringBuilder.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        int fNameLength = TextUtils.isEmpty(fName) ? 0 : fName.length();
        int tNameLength = TextUtils.isEmpty(tName) ? 0 : tName.length();
        int contentLength = contentDecode.length();

        ForegroundColorSpan grayColorSpan = new ForegroundColorSpan(Color.parseColor("#9D9D9D"));
        stringBuilder.setSpan(grayColorSpan, fNameLength + 2 + tNameLength + 1 + contentLength,
                stringBuilder.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        stringBuilder.setSpan(new QMUITouchableSpan(
                Color.parseColor("#67A0FF"),
                Color.parseColor("#67A0FF"),
                Color.parseColor("#00000000"),
                Color.parseColor("#E0E0E0")) {
            @Override
            public void onSpanClick(View view) {
                if (mTextClickListener != null) {
                    mTextClickListener.onTextClick(view, i, 1);
                }
            }
        }, 0, fNameLength, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        stringBuilder.setSpan(new QMUITouchableSpan(
                Color.parseColor("#67A0FF"),
                Color.parseColor("#67A0FF"),
                Color.parseColor("#00000000"),
                Color.parseColor("#E0E0E0")) {
            @Override
            public void onSpanClick(View view) {
                if (mTextClickListener != null) {
                    mTextClickListener.onTextClick(view, i, 2);
                }
            }
        }, 2 + fNameLength, 2 + fNameLength + tNameLength, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        if (mData.get(i).getFormUid().equals(SPUtils.getString(mContext, "uid", null))) {
            stringBuilder.setSpan(new QMUITouchableSpan(
                    Color.parseColor("#67A0FF"),
                    Color.parseColor("#67A0FF"),
                    Color.parseColor("#00000000"),
                    Color.parseColor("#E0E0E0")) {
                @Override
                public void onSpanClick(View view) {
                    if (mTextClickListener != null) {
                        mTextClickListener.onTextClick(view, i, 3);
                    }
                }
            }, stringBuilder.length() - 2, stringBuilder.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        holder.tvReply.setMovementMethodDefault();
        holder.tvReply.setText(stringBuilder);
        holder.tvReply.setTextSize(15);

        holder.tvReply.setTag(position);
        holder.tvReply.setOnClickListener(this);
    }

    public void removeItem(int position){
        final int i = mData.size() - position - 1;
        mData.remove(position);
        notifyItemRemoved(position);
    }

    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }

    @Override
    public void onClick(View view) {
        if (mOnItemClickListener != null){
            mOnItemClickListener.onItemClick(view, (int) view.getTag());
        }
    }

    class mViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_reply)
        QMUISpanTouchFixTextView tvReply;

        public mViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    private String getTime(String timeStamp) {
        long publishTime = Long.parseLong(timeStamp);
        long currentTime = new Date().getTime() / 1000;
        long timeDifference = currentTime - publishTime;
        long timeDifferenceHour = timeDifference / 3600;
        if (timeDifference / 60 < 1) {
            return "刚刚";
        } else if (timeDifferenceHour < 1) {
            return (timeDifference / 60) + "分钟前";
        } else if (timeDifferenceHour < 24) {
            return timeDifferenceHour + "小时前";
        } else if (timeDifferenceHour / 24 < 30) {
            return (timeDifferenceHour / 24) + "天前";
        } else {
            return DateUtil.getStrTime(timeStamp);
        }
    }

    /**
     * 条目点击事件
     */
    public interface OnItemClickListener {
        void onItemClick(View view, int childPosition);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    /**
     * 文本点击事件
     */
    public interface TextClickListener {
        void onTextClick(View view, int itemposition, int tvposition);
    }

    public void setTextClickListener(TextClickListener listener) {
        this.mTextClickListener = listener;
    }

}
